package com.example.demo.security;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author liuhe
 * @date 2020/09/17
 */
public class Base64Test {
    public static void main(String[] args) {
        base64();
        String md5Var = encryptMD5("哈");
        System.out.println(md5Var);
    }

    private static String encryptMD5(String str) {
        try {
            byte[] bytes = str.getBytes();
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(bytes);
            byte[] digest = messageDigest.digest();
            System.out.println(digest.length);
            // digest()最后确定返回的是md5 hash,返回值是8位字符串，因为md5 hash值是16位的hash值
            return new BigInteger(1, digest).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return str;
    }

    private static void base64() {
        String encodeStr = Base64.getEncoder().encodeToString("哈".getBytes());
        System.out.println("base64加密：" + encodeStr);

        byte[] decode = Base64.getDecoder().decode(encodeStr);
        String decodeStr = new String(decode);
        System.out.println("base64解密：" + decodeStr);
    }
}
